package com.ai.nsa;

import com.ai.nsa.utils.lock.LockFactory;
import com.asiainfo.redis.RedisClient;

import static com.ai.nsa.NSAConstants.UNDERLINE;

/**
 * @author Feng Chen 2017/6/13.
 */
public class DefaultNSASerial implements NSASerial {

    private RedisClient redis;

    public RedisClient getRedis() {
        return redis;
    }

    public void setRedis(RedisClient redis) {
        this.redis = redis;
    }

    @Override
    public String get(String serialNumber, String startTime) {
        String key = key(serialNumber, startTime);
        synchronized (LockFactory.getLock(key)) {
            return "" + redis.incr(key);
        }
    }

    // SECTION: INNER HELPER

    private String key(String serialNumber, String startTime) {
        StringBuilder builder = new StringBuilder();
        builder.append(serialNumber).append(UNDERLINE).append(startTime);
        return builder.toString();
    }


}
